import store from '@/store'
import { ACCESSTOKEN } from '@/store/state-types'

const whiteAPI = [
  '/login/signin',
  '/login/signup',
  '/layout/home',
  '/layout/category',
  '/layout/publish'
]
const inWhiteAPI = function (api) {
  return whiteAPI.includes(api)
}

const getStoreToken = function () {
  return Boolean(store.state.user[ACCESSTOKEN])
}
const toLogin = function (Router) {
  Router.push({
    name: 'login'
  })
}
const routerBeforeEach = function (Router) {
  Router.beforeEach((to, from, next) => {
    const fullPath = to.fullPath
    const verifyResult = inWhiteAPI(fullPath)
    const hasToken = getStoreToken()
    if (verifyResult) return next()
    if (!verifyResult && hasToken) return next()
    toLogin(Router)
  })
}

export default routerBeforeEach
